package com.example.service.impl;

import com.example.context.BaseContext;
import com.example.entity.Inventory;
import com.example.entity.Products;
import com.example.entity.ShoppingCart;
import com.example.entity.StoreShoppingCart;
import com.example.mapper.InventoryDao;
import com.example.mapper.ProductsDao;
import com.example.mapper.StoreShoppingCartDao;
import com.example.result.Result;
import com.example.service.StoreShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 购物车(StoreShoppingCart)表服务实现类
 *
 * @author makejava
 * @since 2024-03-12 16:46:48
 */
@Service("storeShoppingCartService")
public class StoreShoppingCartServiceImpl implements StoreShoppingCartService {
    @Resource
    private StoreShoppingCartDao storeShoppingCartDao;

    @Autowired
    private ProductsDao productsDao;

    @Autowired
    private InventoryDao inventoryDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public StoreShoppingCart queryById(Long id) {
        return this.storeShoppingCartDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param storeShoppingCart 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public Page<StoreShoppingCart> queryByPage(StoreShoppingCart storeShoppingCart, PageRequest pageRequest) {
        long total = this.storeShoppingCartDao.count(storeShoppingCart);
        return new PageImpl<>(this.storeShoppingCartDao.queryAllByLimit(storeShoppingCart, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param storeShoppingCart 实例对象
     * @return 实例对象
     */
    @Override
    public StoreShoppingCart insert(StoreShoppingCart storeShoppingCart) {
        this.storeShoppingCartDao.insert(storeShoppingCart);
        return storeShoppingCart;
    }

    /**
     * 修改数据
     *
     * @param storeShoppingCart 实例对象
     * @return 实例对象
     */
    @Override
    public StoreShoppingCart update(StoreShoppingCart storeShoppingCart) {
        this.storeShoppingCartDao.update(storeShoppingCart);
        return this.queryById(storeShoppingCart.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.storeShoppingCartDao.deleteById(id) > 0;
    }

    @Override
    @Transactional
    public Result add(StoreShoppingCart shoppingCart) {
        Long userId = BaseContext.getCurrentId();
        Long storeId = BaseContext.getCurrentId2();
        shoppingCart.setUserId(userId);
        shoppingCart.setStoreId(storeId);
        List<StoreShoppingCart> list = storeShoppingCartDao.list(shoppingCart);

        //如果已存在，数量+1
        if(list != null && list.size()>0){
            //查询库存数量是否已达上限
            List<Inventory> inventoryList = inventoryDao.queryByProductIdAndStoreId(list.get(0).getProductId(),list.get(0).getStoreId());
            StoreShoppingCart cart = list.get(0);
            if (inventoryList.get(0).getProductNum() <= cart.getNumber()){
                return Result.error("该商品已达库存上限");
            }

            cart.setNumber(cart.getNumber() + 1);
            storeShoppingCartDao.updateNumberById(cart);
        }else{
            //如果不存在，需要插入一条购物车数据
            Long productId = shoppingCart.getProductId();
            if(productId!=null){
                //判断是否库存为0
                List<Inventory> inventoryList = inventoryDao.queryByProductIdAndStoreId(shoppingCart.getProductId(),shoppingCart.getStoreId());
                if (inventoryList.get(0).getProductNum() == 0){
                    return Result.error("该商品已达库存为0，无法添加");
                }
                //本次添加到购物车的是商品
                Products products = productsDao.getById(productId);
                shoppingCart.setName(products.getName());
                shoppingCart.setImage(products.getImage());
                shoppingCart.setAmount(products.getPrice());
            }
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            storeShoppingCartDao.insert(shoppingCart);
        }

        return Result.success(shoppingCart);
    }

    @Override
    public List<StoreShoppingCart> showShoppingCart(Long storeId) {
        StoreShoppingCart shoppingCart = StoreShoppingCart.builder()
                .storeId(storeId)
                .build();
        List<StoreShoppingCart> list = storeShoppingCartDao.list(shoppingCart);
        return list;
    }

    @Override
    public Result cleanShoppingCart(Long storeId) {
        storeShoppingCartDao.deleteByStoreId(storeId);
        return Result.success();
    }

    @Override
    public Result sub(StoreShoppingCart storeShoppingCart) {
        Long productId = storeShoppingCart.getProductId();
        if(productId != null ){
            List<StoreShoppingCart> list = storeShoppingCartDao.list(storeShoppingCart);
            Integer number = list.get(0).getNumber();
            if(list.get(0).getNumber()>1){
                list.get(0).setNumber(number-1);
                storeShoppingCartDao.updateNumberById(list.get(0));
            }else{
                storeShoppingCartDao.deleteById(list.get(0).getId());
            }
        }
        return Result.success();
    }
}
